
package linuxbox.bbs.servlet;

import javax.servlet.http.*;

import linuxbox.BoxStatic;
import linuxbox.common.*;
import linuxbox.util.*;
import linuxbox.bbs.bean.*;
import linuxbox.bbs.logic.*;

public class BbsViewAction extends Action {
	protected static String successJSP = null;
	
    public void doAction(HttpSession aSession, BoxSession aBoxSession, 
    HttpServletRequest req, HttpServletResponse res) throws Exception {
		BoxStatic.logger.debug("Beginning of BbsView ... ");
		
		String sCatID = req.getParameter("CAT_ID");
		int iCatID = 0;
		if (sCatID != null && sCatID.length() > 0)
			iCatID = Integer.parseInt(sCatID);

		BbsManager bm = BbsManager.getInstance();
		String sCatName = bm.getCatName(iCatID);

		String sMsgID = req.getParameter("MSG_ID");
		String sTopicID = req.getParameter("TOPIC_ID");
		
		long lMsgID = -1;
		long lTopicID = -1;
		
		if (sMsgID != null && !sMsgID.equals(""))
			lMsgID = Long.parseLong(sMsgID);

		if (sTopicID != null && !sTopicID.equals(""))
			lTopicID = Long.parseLong(sTopicID);
			
		if (lMsgID == -1)
			lMsgID = bm.getFirstMsgID(lTopicID);
			
		BbsMsg msg = bm.getBbsMsg(new BbsMsgKey(lMsgID));
		
		if (lTopicID == -1)
			lTopicID = msg.getTopicID();
			
		String sAuthor = msg.getAuthor();
		String sSubject = msg.getSubject();
		String sMsgBody = msg.getMsgBody();
		int iIndLvl = msg.getIndLvl();
		java.sql.Date dtSubDate = msg.getSubDate();
		java.sql.Time tmSubTime = msg.getSubTime();
		
		int len = sMsgBody.length();
		String sTmp = "";
		if (len >= 6) {
			sTmp = sMsgBody.substring(0, 6);
			if (sTmp.equals("<html>")) {
				sTmp = "<pre>" + sMsgBody.substring(6, len - 6) + "</pre>";
			} else
				sTmp = WebTools.encodeHtml(sMsgBody);	
		} else {
			sTmp = WebTools.encodeHtml(sMsgBody);
		}

		req.setAttribute("TOPIC_ID", Long.toString(lTopicID));
		req.setAttribute("MSG_ID", Long.toString(lMsgID));
		req.setAttribute("IND_LVL", Integer.toString(iIndLvl));
		req.setAttribute("SUBJECT", sSubject);
		req.setAttribute("MSG_BODY", sTmp);
		req.setAttribute("CAT_ID", sCatID);
		req.setAttribute("CAT_NAME", sCatName);
		req.setAttribute("AUTHOR", sAuthor);
		req.setAttribute("SUB_DATE", dtSubDate.toString());
		req.setAttribute("SUB_TIME", tmSubTime.toString());
		
		long lPrevTopic = bm.getPrevTopic(lTopicID, iCatID);
		if (lPrevTopic != -1)
			req.setAttribute("PREV_TOPIC", Long.toString(lPrevTopic));
		else
			req.setAttribute("PREV_TOPIC", null);
		
		long lNextTopic = bm.getNextTopic(lTopicID, iCatID);
		if (lNextTopic != -1)
			req.setAttribute("NEXT_TOPIC", Long.toString(lNextTopic));
		else
			req.setAttribute("NEXT_TOPIC", null);
		
		sendFile(successJSP, req, res);

		BoxStatic.logger.debug("End of BbsView ... ");
	}

	public void setSuccessJSP(String str) {
		successJSP = str;
	}
}
